package com.qf.interceptor;

import com.qf.annotation.NoLogin;
import com.qf.common.JwtUtils;
import com.qf.common.UserUtils;
import com.qf.exception.CustomerException;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author zdl
 * @date 2025/3/24
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断接口中带有@NoLogin注解的是否登录  springboot中，将控制层方法封装成一个hadnlerMethod对象
        if (handler instanceof HandlerMethod) {
            // 将对象装维HandlerMethod
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 根据handlerMethod获取方法对象
            Method method = handlerMethod.getMethod();
            // 判断方法是否带有@NoLogin注解
            if (method.isAnnotationPresent(NoLogin.class)) {
                return true;
            }
            String token = request.getHeader("Token");
            System.out.println("token为：" + token);
            if (!StringUtils.hasLength(token)) {
                throw new CustomerException("1001", "请登录1");
            }
            // 校验token
            try {
                Claims claims = JwtUtils.parseJWT(token);
                Integer uid = claims.get("uid", Integer.class);
                if (uid == null) {
                    throw new CustomerException("1001", "请登录2");
                }
                //将用户信息 存入threadLocal
                UserUtils.setUser(uid);
                System.out.println("当前用户id为：" + uid);
            } catch (Exception e) {
                throw new CustomerException("1001", "请登录3");
            }
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtils.removeUser();
    }
}
